import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    phone: sessionStorage.getItem('phone'),
    phoneHide: sessionStorage.getItem('phoneHide'),
    phoneState: sessionStorage.getItem('phoneState'),
    list: [],
    add: 0,
    trolleyList: []
  },
  mutations: {
    //修改地址状态
    phoneValue(state, phones) {
      state.phoneHide = phones[0];
      state.phone = phones[1];
      // console.log(phones[0])
      //退出登录判断phones控制phoneState状态
      if (phones == "") {
        state.phoneState = false
      } else {
        state.phoneState = true
      }
    },
    //添加收货地址
    AddAddress(state, content) {
      //如果默认选项为true，则其它地址改为false
      if (content.isDefault) {
        state.list.forEach(item => {
          item.isDefault = false
        })
      }
      //将新增地址加工添加至list数组
      state.add++
      let AddressList = {
        id: `${state.add}`,
        name: `${content.name}`,
        tel: `${content.tel}`,
        address: `${content.province,content.addressDetail}`,
        isDefault: JSON.parse(`${content.isDefault}`)
      };
      state.list.push(AddressList)
    },
    //添加购物车
    trolley(state, trolley) {
      let list = state.trolleyList
      //将bid唯一标识的商品对象加工
      let trolleyList = {
        id: `${trolley.bid}`,
        is_checked: false,
        title: `${trolley.title}`,
        price: `${trolley.price}`,
        pic: `${trolley.pic3}`,
        count: 1
      }
      // console.log(state.trolleyList)
      //如果该bid商品已存在，数量加一,修改add为false
      var add = true
      list.forEach(item => {
        if (trolley.bid == item.id) {
          item.count++
          add = false
          return
        }
      })
      //如果add为true,商品对象没有重复，则添加至数组，否则为false.说明商品对象已经存在
      if (add) {
        list.push(trolleyList)
      }
    },
    //删除商品对象
    delete(state, Newarr) {
      state.trolleyList = Newarr
    }
  },
  actions: {},
  modules: {}
})